/* TABLE 1 IN COSAR, GRIECO AND TINTELNOT (2014) 
Inputs: 
- danish_data_9596.dta
- german_data_9596.dta
Outputs: 
- table1.xls
*/

clear
global path "C:\Users\Felix Tintelnot\Dropbox\WindBorder\RestatCGTReplication"

use "$path\Data\output_files\danish_data_9596.dta" 
append using "$path\Data\output_files\german_data_9596.dta" 

keep if type == "LAND"
save temp,replace

// Identify large firms (top 10 producers)
gen id = 1
collapse (sum) id,by(prod)
rename id projects
egen totalprojects=total(projects)
gen mrkshareOverall = 100*projects/totalprojects
gsort -mrkshareOverall 
drop if prod=="Lagerwey"
gen id = _n
keep if id<11
drop projects totalprojects mrkshareOverall

merge 1:m prod using temp

gen market = "DE"
replace market = "DK" if denmark==1
drop germany denmark
gen largefirm = 0 
replace largefirm=1 if _merge ==3

keep prod prodc largefirm market
sort prod market

// Market shares by country
gen id = 1
by prod market: egen projectsMarket=total(id)
sort market 
by market: egen totalprojectsMarket= total(id)
drop id

gen mrkshares = 100*projectsMarket/totalprojectsMarket
gsort -mrkshares 

keep if largefirm==1
collapse (mean) mrkshares,by(prod prodc market)
sort market -mrkshares

gen id =1 
reshape wide mrkshares,i(prod prodc) j(market) string
order prod prodc mrksharesDK mrksharesDE
gsort prodc -mrksharesDE -mrksharesDK
drop id 
replace mrksharesDK=0 if mrksharesDK==.
replace mrksharesDE=0 if mrksharesDE==.

// Write table to excel file
export excel using "$path\SummaryStatistics\table1.xls", replace firstrow(variables)
erase temp.dta
